package com.tsinghuabigdata.edu.ddmath.module.ddwork.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.DDWorkUtil;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.LocalQuestionInfo;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.QuestionType;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.view.QuestionTextView;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.view.CorrectImageUtil;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AppLog;
import com.tsinghuabigdata.edu.ddmath.util.BitmapUtils;
import com.tsinghuabigdata.edu.ddmath.util.PicassoUtil;

import java.io.File;
import java.util.ArrayList;

/**
 * 每页错题信息列表
 */
public class DDWorkQuestionAdapter extends BaseAdapter {

    private Context mContext;
    private LayoutInflater mInflater;
    private ArrayList<QuestionType> mQuestionTypeList = new ArrayList<>();

    private LoginInfo loginInfo;

    private CorrectImageUtil correctImageUtil;
    private CorrectUpdateListener updateListener;

    private ArrayList<QuestionType> questionTypeList = new ArrayList<>();

    private String numberStr[] = {"一","二","三","四","五","六","七","八","九","十"};

    private int currPageNum = 1;


    public DDWorkQuestionAdapter(Context context ) {
        this.mContext = context;
        loginInfo   = AccountUtils.getLoginUser();
        correctImageUtil = new CorrectImageUtil( mContext );

        mInflater=(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);//LayoutInflater.from(mContext);
    }

    public void addQuestionList( ArrayList<LocalQuestionInfo> qlist, int pageNum ){
        for( LocalQuestionInfo question : qlist ){
            addQuestion( question );
        }
        currPageNum = pageNum;
    }

    public void setUpdateListener( CorrectUpdateListener listener ){
        updateListener = listener;
    }

    public void clear(){
        mQuestionTypeList.clear();
    }

    public void addQuestion( LocalQuestionInfo question){
        //先分析日期
        QuestionType item = getQuestionType( question.getQuestionType() );
        item.getQuestionList().add( question );
        //Collections.sort( item.getList(), new QuestionComparator() );
    }

    public void addQuestionType( String type, int pagenum ){
        int index;
        for( index = 0; index < questionTypeList.size(); index++ ){
            QuestionType questionType = questionTypeList.get(index);
            if( questionType.getQustionType().equals(type) ) return;
        }

        //
        QuestionType questionType = new QuestionType();
        questionType.setQustionType( type );
        questionType.setPageNum( pagenum );
        questionType.setShowIndex( index );
        questionTypeList.add( questionType );
    }

    public QuestionType queryQuestionType( String type ){
        for( QuestionType questionType : questionTypeList ){
            if( questionType.getQustionType().equals(type) ) return questionType;
        }
        return null;
    }

    @Override
    public int getCount() {
        int count = 0;
        for( QuestionType item : mQuestionTypeList ){
            count++;
            count += item.getQuestionList().size();
        }
        return count;
    }
    @Override
    public Object getItem(int position) {
        int count = 0;
        for( QuestionType item : mQuestionTypeList ){

            if( count == position )
                return item;
            count++;

            if( position >= count && position < count + item.getQuestionList().size() ){
                return item.getQuestionList().get( position-count );
            }
            count += item.getQuestionList().size();
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;
        if(convertView==null){
            convertView = mInflater.inflate(R.layout.item_ddwork_question, parent, false );
            holder = new ViewHolder(convertView);
            convertView.setTag( holder );
        }else{
            holder=(ViewHolder)convertView.getTag();
        }

        holder.bindView( position );
        return convertView;
    }
    //-------------------------------------------------------------------------------

    private QuestionType getQuestionType( String type ){
        for( QuestionType item : mQuestionTypeList ){
            if( item.getQustionType().equals( type) )
                return item;
        }
        QuestionType item = new QuestionType();
        item.setQustionType( type );
        mQuestionTypeList.add( item );
        //Collections.sort(mQuestionTypeList, new DateComparator() );
        return item;
    }
    //-------------------------------------------------------------------------------
    class ViewHolder{

        private int position;

        private TextView questionTypeView;

        private LinearLayout questionDataLayout;

        private QuestionTextView questionTextView;         //
        private ImageView answerImage;       //题干图

        public ViewHolder(View root ){
            questionTypeView    = (TextView)root.findViewById( R.id.item_ddwork_questiontype );

            questionDataLayout   = (LinearLayout) root.findViewById( R.id.item_ddwork_questionlayout );
            questionTextView     = (QuestionTextView)root.findViewById( R.id.item_ddwork_questiondata );

            answerImage     = (ImageView)root.findViewById( R.id.item_ddwork_answerimage );
            //answerImage.setOnClickListener( this );
        }

        public void bindView( int position ){
            //------------------------------------------------------------------------
            //记录显示的序号
            this.position = position;

            Object object = getItem( position );
            if( object instanceof QuestionType ){
                QuestionType item = (QuestionType)object;

                //questionTypeView.setVisibility( View.VISIBLE );
                questionDataLayout.setVisibility( View.GONE );

                QuestionType questionType = queryQuestionType( item.getQustionType() );
                if( questionType.getPageNum() == currPageNum ){
                    questionTypeView.setVisibility( View.VISIBLE );
                    String data = getNumberStr(questionType.getShowIndex()) +", " + DDWorkUtil.getQuestionTypeName(item.getQustionType());
                    questionTypeView.setText( data );
                }else{
                    questionTypeView.setVisibility( View.GONE );
                }
            }else if( object instanceof LocalQuestionInfo ){

                questionTypeView.setVisibility( View.GONE );
                questionDataLayout.setVisibility( View.VISIBLE );

                LocalQuestionInfo questionInfo = (LocalQuestionInfo)object;
                questionTextView.setQuestion( questionInfo );

                if( !TextUtils.isEmpty(questionInfo.getLocalpath()) ){      //加载本地图片
                    answerImage.setVisibility( View.VISIBLE );
                    Picasso.with(mContext).load( new File( questionInfo.getLocalpath() ) ).error( R.drawable.ic_broken_image ).placeholder(R.drawable.ic_temporary_image).into( answerImage );
                }else if( !TextUtils.isEmpty(questionInfo.getAnswerUrl()) ){    //网络图片
                    answerImage.setVisibility( View.VISIBLE );
                    final String url = BitmapUtils.getUrlQuality( loginInfo.getFileServer()+questionInfo.getAnswerUrl(), 80, loginInfo.getAccessToken() );
                    final String result = questionInfo.getAnswerArea();

                    if( TextUtils.isEmpty(result) || "[]".equals(result) || "null".equals( result ) ){
                        PicassoUtil.getPicasso( mContext ).load( url ).error(R.drawable.ic_broken_image ).placeholder(R.drawable.ic_temporary_image).into(answerImage);
                    }else{
                        PicassoUtil.getPicasso(mContext).load( url).error(R.drawable.ic_broken_image).placeholder(R.drawable.ic_temporary_image).into(answerImage,new Callback() {
                            @Override
                            public void onSuccess() {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Bitmap bitmap = Picasso.with( mContext ).load( url ).get();
                                            final Bitmap dstBitmap = correctImageUtil.getCorrectBitmap( url, bitmap, result );
                                            if(updateListener!=null)updateListener.updateImage( answerImage, dstBitmap );
                                        }catch (Exception e){
                                            e.printStackTrace();
                                        }
                                    }
                                }).start();
                            }
                            @Override
                            public void onError() {
                                AppLog.d("dfdfdfssss  get error url=" + url );
                            }
                        });
                    }


                }else{
                    answerImage.setVisibility( View.INVISIBLE );
                }
            }
        }
    }

    private String getNumberStr(int index ){
        if( index < 0 || index > 10 )
            return "";
        return numberStr[index];
    }

    public interface CorrectUpdateListener{
        void updateImage( ImageView answerImage, Bitmap dstBitmap );
    }

//    class DateComparator implements Comparator<QuestionType> {
//        @Override
//        public int compare(QuestionType lhs, QuestionType rhs) {
//
//            Calendar calendar = Calendar.getInstance();
//            try{
//                calendar.setTime( DateUtils.parse( lhs.getDate() ) );
//                long ltime = calendar.getTimeInMillis();
//                calendar.setTime( DateUtils.parse( rhs.getDate() ));
//                long rtime = calendar.getTimeInMillis();
//
//                int value = 0;
//                if( rtime < ltime ) value = -1;
//                else if( rtime > ltime ) value = 1;
//
//                return value;
//            }catch (Exception e){
//                AppLog.i("DATE",e.toString());
//            }
//            return 0;
//        }
//    }
//
//    class QuestionComparator implements Comparator<ErrorQuestion> {
//        @Override
//        public int compare(ErrorQuestion lhs, ErrorQuestion rhs) {
//
//            Calendar calendar = Calendar.getInstance();
//            try{
//                calendar.setTime( DateUtils.parse( lhs.getCreateTime(), DateUtils.FORMAT_DATA_TIME ) );
//                long ltime = calendar.getTimeInMillis();
//                calendar.setTime( DateUtils.parse( rhs.getCreateTime(), DateUtils.FORMAT_DATA_TIME ));
//                long rtime = calendar.getTimeInMillis();
//
//                int value = 0;
//                if( rtime < ltime ) value = -1;
//                else if( rtime > ltime ) value = 1;
//
//                return value;
//            }catch (Exception e){
//                AppLog.i("DATE",e.toString());
//            }
//            return 0;
//        }
//    }
}